package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"my-new-gin/commonfunc"
	"my-new-gin/jwtauth"
)

func Authorization() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.Request.Header.Get("token")
		fmt.Println("token => ", tokenString)
		if tokenString == "" {
			commonfunc.ReqUnauthorized(c, "Unauthorized")
			c.Abort()
		}
		tokenInfo, newTokenString, err := jwtauth.RefreshToken(jwtauth.Key, tokenString)
		if err != nil {
			commonfunc.ReqUnauthorized(c, "Unauthorized")
			c.Abort()
		}
		c.Writer.Header().Set("Token", newTokenString)
		c.Header("Token", newTokenString)
		c.Set("TokenInfo", tokenInfo)
		c.Set("Token", newTokenString)
		c.Next()
	}
}
